package com.yb.web.shoper;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import com.opensymphony.xwork2.ActionContext;
import com.yb.base.web.BaseAction;
import com.yb.bussiness.global.SysUserService;
import com.yb.bussiness.global.SysUserServiceImpl;
import com.yb.bussiness.global.SystemLogService;
import com.yb.bussiness.global.SystemLogServiceImpl;
import com.yb.bussiness.goods.CategoryService;
import com.yb.bussiness.goods.CategoryServiceImpl;
import com.yb.bussiness.goods.GoodsService;
import com.yb.bussiness.goods.GoodsServiceImpl;
import com.yb.bussiness.goods.ProductService;
import com.yb.bussiness.goods.ProductServiceImpl;
import com.yb.bussiness.goods.TBrandTypeService;
import com.yb.bussiness.goods.TBrandTypeServiceImpl;
import com.yb.bussiness.member.MemberService;
import com.yb.bussiness.member.MemberServiceImpl;
import com.yb.bussiness.shoper.BrandService;
import com.yb.bussiness.shoper.BrandServiceImpl;
import com.yb.bussiness.shoper.ShoperMessageService;
import com.yb.bussiness.shoper.ShoperMessageServiceImpl;
import com.yb.bussiness.shoper.TgCaseService;
import com.yb.bussiness.shoper.TgCaseServiceImpl;
import com.yb.bussiness.shoper.TgFavorableService;
import com.yb.bussiness.shoper.TgFavorableServiceImpl;
import com.yb.bussiness.shoper.TgPingJiaService;
import com.yb.bussiness.shoper.TgPingJiaServiceImpl;
import com.yb.bussiness.shoper.TgStoreService;
import com.yb.bussiness.shoper.TgStoreServiceImpl;
import com.yb.bussiness.shoper.TpBugRecordService;
import com.yb.bussiness.shoper.TpBuyRecordServiceImpl;
import com.yb.bussiness.type.TypeService;
import com.yb.bussiness.type.TypeServiceImpl;
import com.yb.domain.goods.ShoperMessage;
import com.yb.domain.goods.TBrandType;
import com.yb.domain.goods.TgBrand;
import com.yb.domain.goods.TgCase;
import com.yb.domain.goods.TgCategory;
import com.yb.domain.goods.TgFavorable;
import com.yb.domain.goods.TgGoods;
import com.yb.domain.goods.TgInformation;
import com.yb.domain.goods.TgPingJia;
import com.yb.domain.goods.TgProduct;
import com.yb.domain.goods.TgStore;
import com.yb.domain.goods.TgType;
import com.yb.domain.goods.TpBuyRecord;
import com.yb.domain.member.TsSysuser;
import com.yb.util.comm.BASE64Util;
import com.yb.util.comm.Contants;
import com.yb.util.comm.DateTimeUtil;
import com.yb.util.comm.RequestUtil;
import com.yb.util.file.FileUtil;
import com.yb.util.file.XmlUtil;
import com.yb.util.framework.MemoryData;
import com.yb.util.framework.PageUtil;

public class BrandAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = -6987652824265431687L;
	private TgBrand tgBrand;
	private TgStore store;
	private TsSysuser user;
	private TgFavorable favorable;
	private TgCase cases;
	private ShoperMessage sMessage;
	private int total;
	private File imglog;
	private String imglogFileName;
	private File imgpic;
	private String imgpicFileName;
	private File imgcomp;
	private String imgcompFileName;
	private File imgcomp1;
	private String imgcomp1FileName;
	private File imgcomp2;
	private String imgcomp2FileName;
	private File imgcomp3;
	private String imgcomp3FileName;
	@SuppressWarnings("unchecked")
	private List rows;
	private Long id;
	private Long bid;
	private Long categoryId;
	private String[] typeId;

	private BrandService service;
	private ShoperMessageService shoperMessageService;
	private CategoryService categoryService;
	private SysUserService userservice;
	private TBrandTypeService brandService;
	private TypeService typeService;
	private TpBugRecordService recordService;
	private TgPingJiaService pingJiaService;
	private TgStoreService tgStoreService;
	private TgFavorableService tgFavorableService;
	private TgCaseService tgCaseService;
	private GoodsService goodsservice;
	private ProductService productService;
	private MemberService memberService;
	private SystemLogService systemLogService;

	public BrandAction() {
		goodsservice = new GoodsServiceImpl();
		service = new BrandServiceImpl();
		userservice = new SysUserServiceImpl();
		categoryService = new CategoryServiceImpl();
		brandService = new TBrandTypeServiceImpl();
		shoperMessageService = new ShoperMessageServiceImpl();
		typeService = new TypeServiceImpl();
		recordService = new TpBuyRecordServiceImpl();
		pingJiaService = new TgPingJiaServiceImpl();
		tgStoreService = new TgStoreServiceImpl();
		tgFavorableService = new TgFavorableServiceImpl();
		tgCaseService = new TgCaseServiceImpl();
		productService = new ProductServiceImpl();
		memberService = new MemberServiceImpl();
		systemLogService = new SystemLogServiceImpl();
	}

	/**
	 * 商家信息查询
	 * 
	 * @return
	 */
	public String search() {
		String type = RequestUtil.getParam(request, "type", "");
		String page = RequestUtil.getParam(request, "page", "1");
		String row = RequestUtil.getParam(request, "rows", "10");
		String name = RequestUtil.getParam(request, "name", "");
		String auding = RequestUtil.getParam(request, "auding", "");
		String activityFlag = RequestUtil.getParam(request, "activityFlag", "");

		Map<String, String> parameMap = new HashMap<String, String>();
		parameMap.put("type", type);
		parameMap.put("page", page);
		parameMap.put("row", row);
		parameMap.put("name", name);
		parameMap.put("auding", auding);
		parameMap.put("activityFlag", activityFlag);
		List<TgBrand> bradlist = service.findAllShoper(parameMap);
		int count = service.count(parameMap);
		if (bradlist != null) {
			total = count;
			rows = bradlist;
		}
		return Contants.JSONSTRING_RESULT_NAME;
	}

	

    public String loadremind(){
           PrintWriter out;
           try{
               Map<String, String> parameMap = new HashMap<String, String>();
               parameMap.put("auding", "0");
               response.reset();
               response.setCharacterEncoding("utf-8");
               out = response.getWriter();
               Integer count = service.count(parameMap);
               out.write(count+"");
           }catch (Exception e) {
               log.error("加载新增的申请", e);
           }
           return null;
       }
	
	
	/**
	 * 广告管理中查找未加入广告的品牌
	 * 
	 * @return
	 */
	public String searchWithOutAd() {
		String name = RequestUtil.getParam(request, "name", "");
		List<TgBrand> bradlist = service.findByKeyWord(name);
		if (bradlist != null) {
			rows = bradlist;
		}
		return Contants.JSONSTRING_RESULT_NAME;
	}

	public String searchPingou4IndexByKey() {
		try {
			String name = RequestUtil.getParam(request, "name", "");
			Long cid = RequestUtil.getParam(request, "cid", 0l);
			List<TgBrand> bradlist = service.searchPingou4IndexByKey(name, cid);
			if (bradlist != null) {
				rows = bradlist;
			}
		} catch (Exception e) {
			log.error("", e);
		}
		return Contants.JSONSTRING_RESULT_NAME;
	}

	/**
	 * 修改商家信息
	 * 
	 * @return
	 */
	public String addSaveOrUpdate() {
		try {
			user.setPassword(BASE64Util.getBASE64(user.getPassword()));
			//管理员分配账号
			user.setSource("1");
			boolean isFlag = userservice.saveOrUpdate(user);
			if (isFlag) {
				TsSysuser tsSys = userservice.checkRegister(user.getUsername());
				if (null != tsSys) {
					tgBrand.setSysuserId(tsSys.getId());
					String basePath = request.getSession().getServletContext()
							.getRealPath("/");
					String compressPath = XmlUtil.getValue("imgPath",
							"sysConfig")
							+ "/";

					if (imglog != null) {
						String fileName = "";
						fileName = "imglog"+ new Date().getTime()
								+ imglogFileName.substring(imglogFileName
										.lastIndexOf("."));
						if (FileUtil.doUpFile(basePath + compressPath
								+ fileName, imglog)) {
							tgBrand.setImgsrc(compressPath + fileName);
						}
					}
					if (imgpic != null) {
						String picName = "";
						picName ="imgpic" + new Date().getTime()
								+ imgpicFileName.substring(imgpicFileName
										.lastIndexOf("."));
						if (FileUtil.doUpFile(
								basePath + compressPath + picName, imgpic)) {
							tgBrand.setBrandPic(compressPath + picName);
						}
					}
					if (null == tgBrand.getAuding()
							|| "".equals(tgBrand.getAuding())) {
						tgBrand.setAuding("1");
					}
					if (service.saveOrUpdate(tgBrand)){
						 if(tgBrand.getId() == null)
							 systemLogService.saveSystemLog(request, "商家管理", "新增商家--"+tgBrand.getName());
						 else
							 systemLogService.saveSystemLog(request, "商家管理", "修改商家--"+tgBrand.getName());
						return "success";
					}
					return "error";
				}
			}
			return "error";
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}

	}

	public String addSaveShoper() {
		try {
			TsSysuser tsSysuser = (TsSysuser) RequestUtil
					.getLoginUserFromSession(request, Contants.SESSION_USER);
			if (null != tsSysuser) {
				tgBrand.setSysuserId(tsSysuser.getId());
				String basePath = request.getSession().getServletContext()
						.getRealPath("/");
				String compressPath = XmlUtil.getValue("imgPath", "sysConfig")
						+ "/";

				if (imglog != null) {
					String fileName = "";
					fileName = new Date().getTime()
							+ imglogFileName.substring(imglogFileName
									.lastIndexOf("."));
					if (FileUtil.doUpFile(basePath + compressPath + fileName,
							imglog)) {
						tgBrand.setImgsrc(compressPath + fileName);
					}
				}
				if (imgpic != null) {
					String picName = "";
					picName = new Date().getTime()
							+ imgpicFileName.substring(imgpicFileName
									.lastIndexOf("."));
					if (FileUtil.doUpFile(basePath + compressPath + picName,
							imgpic)) {
						tgBrand.setBrandPic(compressPath + picName);
					}
				}
				if (service.saveOrUpdate(tgBrand)) {
					if ("2".equals(tsSysuser.getType())) {
						RequestUtil.reSetLoginUser2Session(request,
								"brandInfo", tgBrand);
					}
					return "addshopersucuss";
				}
				return "error";
			}
			return "error";
		} catch (Exception e) {
			log.error("商家信息完善出错", e);
			return "error";
		}

	}

	/**
	 * 修改商家公告
	 * 
	 * @return
	 */
	public String saveAnnouncement() {
		try {
			service.saveOrUpdate(tgBrand);
		} catch (Exception e) {
		}
		return "success";
	}

	public String showInfo() {
		try {
			rows = categoryService.findAll(1, 50);
		} catch (Exception e) {
		}
		return "showInfo";
	}

	/**
	 * 查询单个商家信息
	 */
	public String findMessageById() {
		String flag = RequestUtil.getParam(request, "flag", "");
		try {
			String id = RequestUtil.getParam(request, "id", "");
			TgBrand actObj = service.findById(id);
			if (null != actObj) {
				TsSysuser tsSysuser = userservice.findByUserId(actObj
						.getSysuserId().intValue());
				String newpass = BASE64Util.getFromBASE64(tsSysuser
						.getPassword());
				tsSysuser.setPassword(newpass);
				request.setAttribute("user", tsSysuser);
			}
			request.setAttribute("tgBrand", actObj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if ("1".equals(flag)) {
			return "modifannouncement";
		} else {
			return "modif";
		}
	}

	/**
	 * 审核商家信息
	 * 
	 * @return
	 */
	public String updateMessageById() {
		PrintWriter out = null;
		try {
			out = response.getWriter();
			Long sysuserId = RequestUtil.getParam(request, "sysuserId", 0l);
			String auding = RequestUtil.getParam(request, "autding", "");
			boolean isboolean = service.updateAutingId(sysuserId.toString(),
					auding);
			if ("1".equals(auding)) {
				memberService.onAutding(sysuserId, 2);
			}
			if ("2".equals(auding)) {
				memberService.onAutding(sysuserId, 7);
			}
			out.println("{result:" + isboolean + "}");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	public String deleteById() {
		PrintWriter out = null;
		try {
			out = response.getWriter();
			String idStr = RequestUtil.getParam(request, "ids", "");
			if (service.checkDel(idStr)) {
				String[] delteid = idStr.split("_");
				try {
					for (int i = 0; i < delteid.length; i++) {
						systemLogService.saveSystemLog(request, "商家管理", "删除商家--"+service.findById(delteid[i]).getName());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				boolean isboolean = service.deleteById(idStr);
				out.println("{result:" + isboolean + "}");
			} else {
				out.println("{result:'3'}");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public String showBrandList() {
		try {
			int page = RequestUtil.getParam(request, "page", 1);
			int row = RequestUtil.getParam(request, "rows", 10);
			int start = (page - 1) * row;
			rows = service.findByBrandId(id);
			total = rows.size();
			rows = rows.subList((start > 0 ? start : 0),
					(rows.size() < ((start > 0 ? start : 0) + row) ? rows
							.size() : ((start > 0 ? start : 0) + row)));
		} catch (Exception e) {
			log.error("显示品牌产品分类信息列表出错", e);
		}
		return Contants.JSONSTRING_RESULT_NAME;
	}

	public String showBrandCategoryInfo() {
		try {
			rows = categoryService.findAll(1, 50);
		} catch (Exception e) {
			log.error("显示品牌产品分类错误", e);
		}
		return "bcInfo";
	}

	public String showBrandCategoryInfoDetail() {
		try {
			List<TgCategory> pList = categoryService.findAll(1, 50);
			TgCategory tc = categoryService.findById(categoryId);
			List<TgCategory> cList = categoryService.findByPid(new Long(tc
					.getPid()), -1, -1);
			List<TgType> typeList = typeService.findByCategoryId(categoryId);
			List<TBrandType> btList = brandService.findByBIdAndCid(id,
					categoryId);
			ActionContext.getContext().put("pList", pList);
			ActionContext.getContext().put("cList", cList);
			ActionContext.getContext().put("typeList", typeList);
			ActionContext.getContext().put("btList", btList);
			ActionContext.getContext().put("bid", id);
			ActionContext.getContext().put("pid", tc.getPid());
			ActionContext.getContext().put("cid", categoryId);
		} catch (Exception e) {
			log.error("显示品牌产品分类错误", e);
		}
		return "bcInfoDetail";
	}

	public String saveBrandCategory() {
		try {
			if (null != typeId) {
			    brandService.deleteByBidAndCid(id, categoryId);
				for (int i = 0; i < typeId.length; i++) {
				    TBrandType tbt = new TBrandType();
				    tbt.setBrandId(id);
				    tbt.setCategoryId(categoryId);
				    tbt.setTypeId(new Long(typeId[i]));
				    brandService.save(tbt);
				    }
			} else {
				TBrandType tbt = new TBrandType();
				tbt.setBrandId(id);
				tbt.setCategoryId(categoryId);
				brandService.deleteByBidAndCid(id, categoryId);
				brandService.save(tbt);
			}
		} catch (Exception e) {
			log.error("维护品牌产品信息出错", e);
		}
		return "showBrandList";
	}

	public String saveBrandCategoryDetail() {
		try {
			if (null != typeId) {
			    brandService.deleteByBidAndCid(id, categoryId);
				for (int i = 0; i < typeId.length; i++) {
					TBrandType tbt = new TBrandType();
					tbt.setBrandId(id);
					tbt.setCategoryId(categoryId);
					tbt.setTypeId(new Long(typeId[i]));
					brandService.save(tbt);
				}
			} else {
				TBrandType tbt = new TBrandType();
				tbt.setBrandId(id);
				tbt.setCategoryId(categoryId);
				brandService.deleteByBidAndCid(id, categoryId);
				brandService.save(tbt);
			}
		} catch (Exception e) {
			log.error("维护品牌产品种类出错", e);
		}
		return "showBrandList";
	}

	public String deleteBT() {
		try {
			if (brandService.checkDel(id, categoryId)) {
				brandService.deleteByBidAndCid(id, categoryId);
				response.getWriter().print("1");
			} else {
				response.getWriter().print("3");
			}
		} catch (Exception e) {
			log.error("", e);
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}
	
	public String deleteBTBytype() {
		String typeId = RequestUtil.getParam(request, "typeId", "");
		if("".equals(categoryId)||null==categoryId){
			categoryId = brandService.findCidByType(typeId);
		}
		try {
			if (brandService.checkDel(id, categoryId)) {
				brandService.deleteByBidAndCid(id, categoryId);
				response.getWriter().print("1");
			} else {
				response.getWriter().print("3");
			}
		} catch (Exception e) {
			log.error("", e);
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * 行业类别显示子分类关联商家信息
	 * @return
	 */
	public String showChildrenInfo(){
		try {
			Map<String,String> map = new HashMap<String,String>();
			String categoryId = RequestUtil.getParam(request, "categoryId", "");
			String name = RequestUtil.getParam(request, "name", "");
			String auding = RequestUtil.getParam(request, "auding", "");
			int page = RequestUtil.getParam(request, "page", 1);
			int limit = RequestUtil.getParam(request, "rows", 10);
			String typeId = RequestUtil.getParam(request, "typeId", "");
			map.put("typeId", typeId);
			map.put("categoryId", categoryId);
			map.put("name", name);
			map.put("auding", auding);
			PageUtil pu = service.findBrand(map, page, limit);
			total = pu.getTotalRecords();
			rows = pu.getList();
		} catch (Exception e) {
			log.error("", e);
		}
		return Contants.JSONSTRING_RESULT_NAME;
	}
	
	
	// 为什么有两个TgBrand对象
	public String detailShoper() {
		TsSysuser tsSysuser = (TsSysuser) RequestUtil.getLoginUserFromSession(request, Contants.SESSION_USER);
		try {
			String brandId = RequestUtil.getParam(request, "id", "0");
			Long categoryId = RequestUtil.getParam(request, "categoryId", 0l);
			TgBrand actObj = service.findById(brandId);
			if (0l == categoryId)
				categoryId = actObj.getCid();
			else
				actObj.setCid(categoryId);
			if (null != actObj)
				actObj.setCategoryId(Integer.valueOf(categoryId.toString()));
			// 商家/服务信息
			store = tgStoreService.findStoreBybid(Long.valueOf(brandId));
			ActionContext context = ActionContext.getContext();
			if (store != null) {
				actObj.setStoreContent(store.getStoreContent());
				actObj.setStoreDesc(store.getStoreDesc());
				List<TgInformation> imgInfoList = new ArrayList<TgInformation>();
				if (null != store.getImgSrc1()&&!"".equals(store.getImgSrc1())) {
					TgInformation obj1 = new TgInformation();
					obj1.setImgUrl(store.getImgSrc1());
					imgInfoList.add(obj1);
				}
				if (null != store.getImgSrc2()&&!"".equals(store.getImgSrc2())) {
					TgInformation obj2 = new TgInformation();
					obj2.setImgUrl(store.getImgSrc2());
					imgInfoList.add(obj2);
				}
				if (null != store.getImgSrc3()&&!"".equals(store.getImgSrc3())) {
					TgInformation obj3 = new TgInformation();
					obj3.setImgUrl(store.getImgSrc3());
					imgInfoList.add(obj3);
				}
				context.put("imgInfoList", imgInfoList);
			}

			// 获取参加该品牌拼购的人员
			Map<String, String> parameMap = new HashMap<String, String>();
			parameMap.put("brandid", actObj.getId().toString());
//			parameMap.put("autding", "1");
			List<TpBuyRecord> memberlist = recordService
					.findByParameMap2(parameMap);
			//验证改业主是否已经参加过拼购
//			if(null!=memberlist && memberlist.size()>0 && null!=tsSysuser){
//				context.put("joinPingouFlag", 0);
//				for (int i = 0; i < memberlist.size(); i++) {
//					if(memberlist.get(i).getUserId()==tsSysuser.getId()){
//						context.put("joinPingouFlag", 1);
//						break;
//					}
//				}
//			}
			int counttotal = recordService.counttotal(parameMap);
			// 本月参加人数
			int count = recordService.searchCountByBrandId(actObj.getId()
					.toString());
			context.put("count", count);
			context.put("counttotal", counttotal);
			context.put("memberlist", memberlist);
			context.put("tgBrand", actObj);
            if(null!=actObj.getStoreContent()&&!"".equals(actObj.getStoreContent())){
                context.put("tgBrandflag", "1");
            }
			
			if (categoryId > 0l) {
				TgCategory tg = categoryService.findById(categoryId);
				if (tg != null && tg.getPid() > 0) {
					TgCategory ptg = categoryService.findById(new Long(tg
							.getPid()));
					context.put("pcategory", ptg);
				}
				context.put("category", tg);
			}
			Long id = RequestUtil.getParam(request, "id", 0l);
			int page = RequestUtil.getParam(request, "pageNo", 1);
			int row = RequestUtil.getParam(request, "limit", 12);
			TgBrand brand = service.findById(id + "");

			PageUtil messagePu = new PageUtil();
			if (brand != null) {
				messagePu = shoperMessageService.findMessageByBrandId(id, -1,
						-1);
			}

			// 商家信息每页显示12条。
			List<ShoperMessage> message1List = shoperMessageService
					.findMessage1ByBrandId(id);
			List<ShoperMessage> message2List = shoperMessageService
					.findMessage2ByBrandId(id);
			List<ShoperMessage> message3List = shoperMessageService
					.findMessage3ByBrandId(id);

			// 商家信息
			PageUtil pjPu = pingJiaService.findPjByBrandId(id,"1", 1, 12);
			parameMap.put("brandId", brandId);
			parameMap.put("page", "1");
			parameMap.put("row", "12");
			parameMap.put("auding", "1");
			List<TgCase> bradlist = tgCaseService.findcases(parameMap);
			//查询是否已经评价过该产品
			if(null!=tsSysuser){
				int isPingjia = pingJiaService.isPingjia(id,tsSysuser.getId());
				ActionContext.getContext().put("isPingjia", isPingjia);
			}
			
			// 获取活动
			parameMap.put("row", "1");
			List<TgFavorable> favlist = tgFavorableService
					.findFavorable(parameMap);
			TgFavorable favorable = new TgFavorable();
			if (favlist != null)
				favorable = favlist.get(0);

			PageUtil goodsPu = productService.findByBrandId(id, 1, 8, "");
			ActionContext.getContext().put("brandobj", brand);
			ActionContext.getContext().put(
					"messagePu",
					bulidMessage(message1List, message2List, message3List,
							messagePu, 1, 12));
			ActionContext.getContext().put("pjPu", pjPu);
			ActionContext.getContext().put("goodsPu", goodsPu);
			ActionContext.getContext().put("bradlist", bradlist);
			ActionContext.getContext().put("favorable", favorable);
		} catch (Exception e) {
			log.error("显示商家页面出错", e);
		}
		return "shangjia2";
	}

	@SuppressWarnings("unchecked")
	private PageUtil bulidMessage(List<ShoperMessage> message1List,
			List<ShoperMessage> message2List, List<ShoperMessage> message3List,
			PageUtil messagePu, int page, int limit) {
		int start = (page - 1) * limit;
		PageUtil pu = new PageUtil();
		List<ShoperMessage> newList = new ArrayList<ShoperMessage>();
		if (null != message1List)
			newList.addAll(message1List);
		if (null != message2List)
			newList.addAll(message2List);
		if (null != message3List)
			newList.addAll(message3List);
		List<ShoperMessage> list = (List<ShoperMessage>) messagePu.getList();
		if (null != list)
			newList.addAll(list);
		pu.setTotalRecords(newList.size());
		pu.setList(newList.subList((start > 0 ? start : 0),
				(newList.size() < ((start > 0 ? start : 0) + limit) ? newList
						.size() : ((start > 0 ? start : 0) + limit))));
		pu.setPageNo(page);
		pu.setPageSize(limit);
		return pu;
	}

	public String findAllMessage() {
		int page = RequestUtil.getParam(request, "pageNo", 1);
		int row = RequestUtil.getParam(request, "limit", 12);
		TgBrand brand = service.findById(id + "");
		PageUtil messagePu = new PageUtil();
		if (brand != null) {
			messagePu = shoperMessageService.findMessageByBrandId(id, -1, -1);
		}

		// 商家信息每页显示12条。
		List<ShoperMessage> message1List = shoperMessageService
				.findMessage1ByBrandId(id);
		List<ShoperMessage> message2List = shoperMessageService
				.findMessage2ByBrandId(id);
		List<ShoperMessage> message3List = shoperMessageService
				.findMessage3ByBrandId(id);

		messagePu = bulidMessage(message1List, message2List, message3List,
				messagePu, page, row);

		try {
			response.getWriter().print(JSONArray.fromObject(messagePu));
		} catch (Exception e) {
			log.error("根据行业获取资讯信息", e);
		}
		return null;
	}

	public String findAllEvaluate() {
		int page = RequestUtil.getParam(request, "pageNo", 1);
		int row = RequestUtil.getParam(request, "limit", 12);
		String flag = RequestUtil.getParam(request, "flag", "");
//		TgBrand brand = service.findById(id + "");
		PageUtil pjPu = pingJiaService.findPjByBrandId(id,flag, page, row);
		try {
			response.getWriter().print(JSONArray.fromObject(pjPu));
		} catch (Exception e) {
			log.error("根据行业获取评价信息", e);
		}
		return null;
	}

	// TODO:
	public String changeproductlist() {
		try {
			Map<String, String> parameMap = new HashMap<String, String>();
			Long brandId = RequestUtil.getParam(request, "id", 0l);
			int page = RequestUtil.getParam(request, "page", 0);
			PageUtil goodsPu = productService.findByBrandId(brandId, page, 8,
					"");
			List<TgProduct> glist = new ArrayList<TgProduct>();
			glist = (List<TgProduct>) goodsPu.getList();
			PrintWriter out = response.getWriter();
			if (glist.size() > 0) {
				String jsonsb = "[";
				for (TgProduct product : glist) {
					jsonsb += "{imgSrc:'" + product.getImgsrc() + "',";
					jsonsb += "id:'" + product.getId() + "',";
					jsonsb += "name:'" + product.getTitle() + "'},";
				}
				jsonsb = jsonsb.substring(0, jsonsb.length() - 1);
				jsonsb += "]";
				out.write(jsonsb);
			} else {
				out.write("1");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String changegoodslist() {
		try {
			Map<String, String> parameMap = new HashMap<String, String>();
			String brandId = RequestUtil.getParam(request, "id", "0");
			String page = RequestUtil.getParam(request, "page", "0");
			parameMap.put("brandId", brandId);
			parameMap.put("page", page);
			parameMap.put("auding", "1");
			PageUtil goodsPu = goodsservice.getList(parameMap,
					new Integer(page), 8);
			List<TgGoods> glist = new ArrayList<TgGoods>();
			glist = (List<TgGoods>) goodsPu.getList();
			PrintWriter out = response.getWriter();
			if (glist.size() > 0) {
				String jsonsb = "[";
				for (TgGoods goods : glist) {
					jsonsb += "{imgSrc:'" + goods.getImgSrc() + "',";
					jsonsb += "id:'" + goods.getId() + "',";
					jsonsb += "categoryId:'" + goods.getCategoryId() + "',";
					jsonsb += "name:'" + goods.getName() + "'},";
				}
				jsonsb = jsonsb.substring(0, jsonsb.length() - 1);
				jsonsb += "]";
				out.write(jsonsb);
			} else {
				out.write("1");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String changebradlist() {
		try {
			Map<String, String> parameMap = new HashMap<String, String>();
			String brandId = RequestUtil.getParam(request, "id", "0");
			String page = RequestUtil.getParam(request, "page", "0");
			parameMap.put("brandId", brandId);
			parameMap.put("page", page);
			parameMap.put("row", "6");
			parameMap.put("auding", "1");
			List<TgCase> bradlist = tgCaseService.findcases(parameMap);
			PrintWriter out = response.getWriter();
			if (bradlist.size() > 0) {
				String jsonsb = "[";
				for (TgCase tgCase : bradlist) {
					jsonsb += "{imgSrc:'" + tgCase.getImgSrc() + "',";
					jsonsb += "id:'" + tgCase.getId() + "',";
					jsonsb += "name:'" + tgCase.getTitle() + "'},";
				}
				jsonsb = jsonsb.substring(0, jsonsb.length() - 1);
				jsonsb += "]";
				out.write(jsonsb);
			} else {
				out.write("1");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 根据商家id查找出商家详情信息
	 * 
	 * @return
	 */
	public String detailShoper_old() {
		try {
			String id = RequestUtil.getParam(request, "id", "");
			TgBrand actObj = service.findById(id);
			if (actObj != null) {
				Map<String, String> parameMap = new HashMap<String, String>();
				parameMap.put("autding", "1");
				parameMap.put("brandid", actObj.getId().toString());
				List<TpBuyRecord> memberlist = recordService
						.findByParameMap(parameMap);
				int count = recordService.searchCountByBrandId(actObj.getId()
						.toString());
				// 本月参加人数
				ActionContext.getContext().put("count", count);
				// 已经参加的人
				ActionContext.getContext().put("memberlist", memberlist);
				parameMap.put("shoperId", actObj.getId().toString());
				// 获取类别
				TgCategory chilcategory = categoryService.findById(Long
						.parseLong(actObj.getCategoryId().toString()));
				if (chilcategory != null) {
					actObj.setSecondBrandName(chilcategory.getName());
					TgCategory frisechilcategory = categoryService
							.findById(Long.parseLong(chilcategory.getPid()
									.toString()));
					if (frisechilcategory == null) {

						actObj.setFirseBrandName(chilcategory.getName());
						actObj.setSecondBrandName("");
					} else {
						actObj.setFirseBrandName(frisechilcategory.getName());
					}
				}
			}
			Long categoryId = RequestUtil.getParam(request, "categoryId", 0l);
			if (categoryId > 0l) {
				TgCategory tg = categoryService.findById(categoryId);
				if (tg != null && tg.getPid() > 0) {
					TgCategory ptg = categoryService.findById(new Long(tg
							.getPid()));
					ActionContext.getContext().put("pcategory", ptg);
				}
				ActionContext.getContext().put("category", tg);
			}
			ActionContext.getContext().put("tgBrand", actObj);
			return "shangjia";

		} catch (Exception e) {
			log.error("detailShoper", e);
			e.printStackTrace();
			return "error";
		}
	}

	public String showBrandWeight() {
		try {
			int page = RequestUtil.getParam(request, "page", 1);
			int row = RequestUtil.getParam(request, "rows", 10);
			int start = (page - 1) * row;
			rows = service.findBrandByCategroyId(categoryId);
			total = rows.size();
			rows = rows.subList((start > 0 ? start : 0),
					(rows.size() < ((start > 0 ? start : 0) + row) ? rows
							.size() : ((start > 0 ? start : 0) + row)));
		} catch (Exception e) {
			log.error("品牌权重管理出错", e);
		}
		return Contants.JSONSTRING_RESULT_NAME;
	}

	public String showBrandannocumentWeight() {
		try {
			int page = RequestUtil.getParam(request, "page", 1);
			int row = RequestUtil.getParam(request, "rows", 10);
			int start = (page - 1) * row;
			rows = service.findBrandByAnnocumentCategroyId(categoryId);
			total = rows.size();
			rows = rows.subList((start > 0 ? start : 0),
					(rows.size() < ((start > 0 ? start : 0) + row) ? rows
							.size() : ((start > 0 ? start : 0) + row)));
		} catch (Exception e) {
			log.error("品牌权重管理出错", e);
		}
		return Contants.JSONSTRING_RESULT_NAME;
	}

	/**
	 * 
	 * by zh 2012-05-02
	 * 
	 * @return
	 */
	public String showBrandannocumentWeight_NEW() {
		try {
			int page = RequestUtil.getParam(request, "page", 1);
			int row = RequestUtil.getParam(request, "rows", 50);
			rows = service.findBrandByAnnocumentCategroyId();
		} catch (Exception e) {
			log.error("品牌权重管理出错", e);
		}
		return "showBrandannocumentWeight_NEW";
	}

	public String showFirstCategory() {
		try {
			List<TgCategory> list = categoryService.findAll(1, 50);
			response.getWriter().print(JSONArray.fromObject(list));
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * 根据子类别查找所有符合的品牌
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String findAllBrandByCategory() {
		try {
			Long categoryId = RequestUtil.getParam(request, "categoryId", 0l);
			if (categoryId != 0l) {
				List list = service.findBrandByCategoryId(categoryId);
				response.getWriter().print(JSONArray.fromObject(list));
			}
		} catch (Exception e) {
			log.error("根据子类别查找所有符合的商品出错", e);
			try {
				response.getWriter().print("[]");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 根据产品种类查找所有符合的品牌
	 * 
	 * @return
	 */
	public String findAllBrandByType() {
		try {
			Long typeId = RequestUtil.getParam(request, "typeId", 0l);
			if (typeId != 0l) {
				List list = service.findBrandByTypeId(typeId);
				response.getWriter().print(JSONArray.fromObject(list));
			}
		} catch (Exception e) {
			log.error("根据产品种类查找所有符合的商品出错", e);
			try {
				response.getWriter().print("[]");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	public String deleteBrandHot() {
		try {
			Long categoryId = RequestUtil.getParam(request, "categoryId", 0l);
			Long brandId = RequestUtil.getParam(request, "brandId", 0l);
			service.deleteBrandHot(categoryId, brandId);
			response.getWriter().print("1");
		} catch (Exception e) {
			log.error("删除种类品牌权重失败", e);
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 删除广告位
	 * 
	 * @return
	 */
	public String deleteanncumentBrandHot() {
		try {
			Long categoryId = RequestUtil.getParam(request, "categoryId", 0l);
			Long brandId = RequestUtil.getParam(request, "brandId", 0l);
			service.deleteancumentBrandHot(categoryId, brandId);
			response.getWriter().print("1");
		} catch (Exception e) {
			log.error("删除种类品牌权重失败", e);
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 删除广告位
	 * 
	 * @return
	 */
	public String deleteancumentBrandHot_NEW() {
		try {
			Long cid = RequestUtil.getParam(request, "cid", 0l);
			service.deleteancumentBrandHot(cid);
			response.getWriter().print("1");
		} catch (Exception e) {
			log.error("删除种类品牌权重失败", e);
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	public String updateBrandWeights() {
		try {
			Long categoryId = RequestUtil.getParam(request, "categoryId", 0l);
			Long brandId = RequestUtil.getParam(request, "brandId", 0l);
			Integer weights = RequestUtil.getParam(request, "weights", 1);
			service.updateBrandHot(categoryId, brandId, weights);
			systemLogService.saveSystemLog(request, "首页拼购广告", "修改权重--"+service.findById(brandId.toString()).getName());
			response.getWriter().print("1");
		} catch (Exception e) {
			log.error("删除种类品牌权重失败", e);
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 更改权重
	 * 
	 * @return
	 */
	public String updateBrandWeights_NEW() {
		try {
			Long cid = RequestUtil.getParam(request, "cid", 0l);
			Integer weights = RequestUtil.getParam(request, "weights", 1);
			service.updateBrandHot(cid, weights);
			response.getWriter().print("1");
		} catch (Exception e) {
			log.error("删除种类品牌权重失败", e);
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	
	   /**
     * 更改权重
     * 
     * @return
     */
    public String changeActivity() {
        try {
            String infoId = RequestUtil.getParam(request, "infoId", "");
            String activityflag = RequestUtil.getParam(request, "activityflag", "0");
            service.changeActivity(infoId, activityflag);
            response.getWriter().print("1");
        } catch (Exception e) {
            log.error("商家活动设置失败", e);
            try {
                response.getWriter().print("2");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return null;
    }
	
	/**
	 * 修改广告位权重
	 */
	public String updateannocumentBrandWeights() {
		try {
			Long categoryId = RequestUtil.getParam(request, "categoryId", 0l);
			Long brandId = RequestUtil.getParam(request, "brandId", 0l);
			Integer weights = RequestUtil.getParam(request, "weights", 1);
			service.updateanncumentBrandHot(categoryId, brandId, weights);
			response.getWriter().print("1");
		} catch (Exception e) {
			log.error("删除种类品牌权重失败", e);
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	public String updateBrandCategoryWeights() {
		try {
			Long categoryId = RequestUtil.getParam(request, "categoryId", 0l);
			Long brandId = RequestUtil.getParam(request, "brandId", 0l);
			Long typeId = RequestUtil.getParam(request, "typeId", -1l);
			Integer weights = RequestUtil.getParam(request, "weights", 1);
			service.updateBrandCategoryAd(categoryId, typeId, brandId, weights);
			systemLogService.saveSystemLog(request, "种类资讯广告管理", "修改权重--"+service.findById(brandId.toString()).getName());
			response.getWriter().print("1");
		} catch (Exception e) {
			log.error("删除种类品牌权重失败", e);
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	public String showBrandWeights() {
		try {
			rows = categoryService.findAll(1, 50);
		} catch (Exception e) {
			log.error("", e);
		}
		return "showBrandWeights";
	}

	/**
	 * 跳转到广告位新增页面
	 */
	public String showBrandannocumentWeights() {
		try {
			rows = categoryService.findAll(1, 50);
		} catch (Exception e) {
			log.error("", e);
		}
		return "showBrandannocumentWeights";
	}

	public String saveBrandWeights() {
		try {
			Long bigCategoryId = RequestUtil.getParam(request, "bigCategory",
					0l);
			Long brandId = RequestUtil.getParam(request, "brandId", 0l);
			Integer weights = RequestUtil.getParam(request, "weights", 0);
			if (bigCategoryId != 0l && brandId != 0l) {
				service.saveBrandWeight(bigCategoryId, brandId, weights);
			}
		} catch (Exception e) {
			log.error("", e);
		}
		return "brandWeightsList";
	}

	/**
	 * 保存 广告位
	 * 
	 * @return
	 */

	public String saveannocumentBrandWeights() {
		try {
			Long bigCategoryId = RequestUtil.getParam(request, "bigCategory",
					0l);
			Long brandId = RequestUtil.getParam(request, "brandId", 0l);
			Integer weights = RequestUtil.getParam(request, "weights", 0);
			if (bigCategoryId != 0l && brandId != 0l) {
				service.saveanncoumentBrandWeight(bigCategoryId, brandId,
						weights);
			}
		} catch (Exception e) {
			log.error("", e);
		}
		return "annoucementbrandWeightsList";
	}

	public String findAllBrand() {
		try {
			Long categoryId = RequestUtil.getParam(request, "categoryId", 0l);
			Long typeId = RequestUtil.getParam(request, "typeId", -1l);
			int page = RequestUtil.getParam(request, "page", 1);
			int limit = RequestUtil.getParam(request, "rows", 10);
			PageUtil pu = service.findBrand(categoryId, typeId, page, limit);
			total = pu.getTotalRecords();
			rows = pu.getList();
		} catch (Exception e) {
			log.error("", e);
		}
		return Contants.JSONSTRING_RESULT_NAME;
	}

	public String findAllBrand2() {
		try {
			Long categoryId = RequestUtil.getParam(request, "categoryId",
					MemoryData.getCategoryList().get(0).getId());
			Long typeId = RequestUtil.getParam(request, "typeId", -2l);
			int page = RequestUtil.getParam(request, "page", 1);
			int limit = RequestUtil.getParam(request, "rows", 10);
			PageUtil pu = service.findBrand(categoryId, typeId, page, limit);
			total = pu.getTotalRecords();
			rows = pu.getList();
		} catch (Exception e) {
			log.error("", e);
		}
		return Contants.JSONSTRING_RESULT_NAME;
	}

	public String findAllBrandAll() {
		try {
			Long categoryId = 0l;
			int page = RequestUtil.getParam(request, "page", 1);
			int limit = RequestUtil.getParam(request, "rows", 10);
			PageUtil pu = service.findBrand(categoryId, -1l, page, limit);
			total = pu.getTotalRecords();
			rows = pu.getList();
		} catch (Exception e) {
			log.error("", e);
		}
		return Contants.JSONSTRING_RESULT_NAME;
	}

	public String showBrandCategoryWeights() {
		try {
			rows = categoryService.findAll(1, 50);
		} catch (Exception e) {
			log.error("", e);
		}
		return "showBrandCategoryWeights";
	}
	
	public String showBrandCategoryWeights2() {
		try {
			rows = categoryService.findAll(1, 50);
		} catch (Exception e) {
			log.error("", e);
		}
		return "showBrandCategoryWeights2";
	}

	public String showBrandCategoryWeightsAll() {
		try {
			rows = categoryService.findAll(1, 50);
		} catch (Exception e) {
			log.error("", e);
		}
		return "showBrandCategoryWeightsAll";
	}

	public String showBrandCategoryWeightsIndex() {
		try {
			rows = categoryService.findAll(1, 50);
		} catch (Exception e) {
			log.error("转向行业资讯广告错误", e);
		}
		return "showBrandCategoryWeightsIndex";
	}

	public String saveBrandCategoryWeights() {
		try {
			Long categoryId = RequestUtil.getParam(request, "categoryId", 0l);
			Long typeId = RequestUtil.getParam(request, "typeId", -1l);
			Long brandId = RequestUtil.getParam(request, "brandId", 0l);
			Integer weights = RequestUtil.getParam(request, "weights", 0);
			if (categoryId != 0l && brandId != 0l) {
				service.saveBrandCategoryWeight(categoryId, brandId, typeId,
						weights);
			}
		} catch (Exception e) {
			log.error("", e);
		}
		return "saveBrandCategoryWeights";
	}
	
	public String saveBrandCategoryWeights2() {
		try {
			Long categoryId = RequestUtil.getParam(request, "bigCategory", 0l);
			Long typeId = -2l;
			Long brandId = RequestUtil.getParam(request, "brandId", 0l);
			Integer weights = RequestUtil.getParam(request, "weights", 0);
			if (categoryId != 0l && brandId != 0l) {
				service.saveBrandCategoryWeight(categoryId, brandId, typeId,
						weights);
			}
			tgBrand = service.findById(brandId+"");
            systemLogService.saveSystemLog(request, "种类资讯广告管理", "新增--"+tgBrand.getName());
		} catch (Exception e) {
			log.error("", e);
		}
		return "saveBrandCategoryWeights2";
	}

	public String saveBrandCategoryWeightsAll() {
		try {
			Long categoryId = 0l;
			Long typeId = 0l;
			Long brandId = RequestUtil.getParam(request, "brandId", 0l);
			Integer weights = RequestUtil.getParam(request, "weights", 0);
			service.saveBrandCategoryWeight(categoryId, brandId, typeId,
					weights);
			tgBrand = service.findById(brandId+"");
			systemLogService.saveSystemLog(request, "全站热点广告", "新增--"+tgBrand.getName());
		} catch (Exception e) {
			log.error("", e);
		}
		return "saveBrandCategoryWeightsAll";
	}

	public String saveBrandCategoryWeightsIndex() {
		try {
			Long categoryId = RequestUtil.getParam(request, "bigCategory", 0l);
			Long typeId = 0l;
			Long brandId = RequestUtil.getParam(request, "brandId", 0l);
			Integer weights = RequestUtil.getParam(request, "weights", 0);
			service.saveBrandCategoryWeight(categoryId, brandId, typeId,
					weights);
			tgBrand = service.findById(brandId+"");
            systemLogService.saveSystemLog(request, "行业资讯广告", "新增--"+tgBrand.getName());
		} catch (Exception e) {
			log.error("", e);
		}
		return "saveBrandCategoryWeightsIndex";
	}

	public String searchRightList() {
		String id = RequestUtil.getParam(request, "id", "");
		String page = RequestUtil.getParam(request, "pageNo", "1");
		String row = RequestUtil.getParam(request, "limit", "10");
		PageUtil shoperMessagelist;
		TgBrand actObj = service.findById(id);
		if (actObj != null) {
			Map<String, String> parameMap = new HashMap<String, String>();
			parameMap.put("autding", "1");
			parameMap.put("brandid", actObj.getId().toString());
			parameMap.put("shoperId", actObj.getId().toString());
			HttpSession session = request.getSession();
			session.setAttribute("modifyBrandid", actObj.getId().toString());
			// 商家发布的信息
			List<ShoperMessage> shoplist = shoperMessageService
					.findByParameMap(parameMap);
			int messageCount = shoperMessageService.count(parameMap);
			shoperMessagelist = new PageUtil();
			shoperMessagelist.setList(shoplist);
			shoperMessagelist.setPageNo(Integer.parseInt(page));
			shoperMessagelist.setPageSize(Integer.parseInt(row));
			shoperMessagelist.setTotalRecords(messageCount);
			// 商家发布的信息
			ActionContext.getContext().put("shoplist", shoperMessagelist);

			HashMap<String, String> searchMap = new HashMap<String, String>();
			searchMap.put("brandid", actObj.getId().toString());
			List<TgPingJia> pglist = pingJiaService.searchByParaMap(searchMap);
			// 评价信息
			ActionContext.getContext().put("pglist", pglist);

		}

		ActionContext.getContext().put("brandobj", actObj);
		return "detail";
	}

	public String brandDetail() {
		try {
			Long id = RequestUtil.getParam(request, "id", 0l);
			int page = RequestUtil.getParam(request, "pageNo", 1);
			int row = RequestUtil.getParam(request, "limit", 15);
			TgBrand brand = service.findById(id + "");
			PageUtil messagePu = new PageUtil();
			if (brand != null) {
				messagePu = shoperMessageService.findMessageByBrandId(id, page,
						row);
			}
			List<ShoperMessage> message1List = shoperMessageService
					.findMessage1ByBrandId(id);
			List<ShoperMessage> message2List = shoperMessageService
					.findMessage2ByBrandId(id);
			List<ShoperMessage> message3List = shoperMessageService
					.findMessage3ByBrandId(id);
			ActionContext.getContext().put("brandobj", brand);
			ActionContext.getContext().put("messagePu", messagePu);
			ActionContext.getContext().put("message1List", message1List);
			ActionContext.getContext().put("message2List", message2List);
			ActionContext.getContext().put("message3List", message3List);
		} catch (Exception e) {
			log.error("商家详情显示出错", e);
		}
		return "brandDetail";
	}

	public String brandMessage() {
		try {
			Long id = RequestUtil.getParam(request, "id", 0l);
			int page = RequestUtil.getParam(request, "pageNo", 1);
			int row = RequestUtil.getParam(request, "limit", 10);
			PageUtil messagePu = new PageUtil();
			messagePu = shoperMessageService
					.findMessageByBrandId(id, page, row);
			response.getWriter().print(
					JSONArray.fromObject(messagePu.getList()));
		} catch (Exception e) {
			log.error("显示商家信息失败", e);
			try {
				response.getWriter().print("[]");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	public String brandPingJia() {
		try {
			Long id = RequestUtil.getParam(request, "id", 0l);
			int page = RequestUtil.getParam(request, "pageNo", 1);
			int row = RequestUtil.getParam(request, "limit", 10);
			PageUtil pjPu = new PageUtil();
			pjPu = pingJiaService.findPjByBrandId(id,"1", page, row);
			response.getWriter().print(JSONArray.fromObject(pjPu));
		} catch (Exception e) {
			log.error("显示商家信息失败", e);
			try {
				response.getWriter().print("[]");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	public String showMessage() {
		try {
			List<TgBrand> list = service.findAllBrand();
			ActionContext context = ActionContext.getContext();
			context.put("tglist", list);
			Long messageId = RequestUtil.getParam(request, "messageId", 0l);
			ShoperMessage sm = shoperMessageService.findById(messageId + "");
			TgBrand brand = service.findById(sm.getShoperId() + "");
			context.put("brand", brand);
			context.put("sm", sm);
		} catch (Exception e) {
			log.error("查询资讯信息出错", e);
		}
		return "brandMessage";
	}

	/**
	 * 新增、修改店铺信息
	 * 
	 * @return
	 */
	public String addstore() {
		TsSysuser tsSysuser = (TsSysuser) RequestUtil.getLoginUserFromSession(
				request, Contants.SESSION_USER);
		try {
			String basePath = request.getSession().getServletContext()
					.getRealPath("/");
			String compressPath = XmlUtil.getValue("imgPath", "sysConfig")
					+ "/";
			String fileName = "";
			if (imgcomp1 != null) {
				fileName ="pic1"+ new Date().getTime()
						+ imgcomp1FileName.substring(imgcomp1FileName
								.lastIndexOf("."));
				if (FileUtil.doUpFile(basePath + compressPath + fileName,
						imgcomp1)) {
					store.setImgSrc1(compressPath + fileName);
				}
			}
			String imgDeleteFlag2 = RequestUtil.getParam(request, "imgDeleteFlag2", "");
			String imgDeleteFlag3 = RequestUtil.getParam(request, "imgDeleteFlag3", "");
			if("1".equals(imgDeleteFlag2)&&imgcomp2 == null){
				store.setImgSrc2("");
			}else if (imgcomp2 != null) {
				fileName ="pic2"+ new Date().getTime()
						+ imgcomp2FileName.substring(imgcomp2FileName
								.lastIndexOf("."));
				if (FileUtil.doUpFile(basePath + compressPath + fileName,
						imgcomp2)) {
					store.setImgSrc2(compressPath + fileName);
				}
			}
			if("1".equals(imgDeleteFlag3)&&imgcomp3 == null){
				store.setImgSrc3("");
			}else if (imgcomp3 != null) {
				fileName ="pic3"+ new Date().getTime()
						+ imgcomp3FileName.substring(imgcomp3FileName
								.lastIndexOf("."));
				if (FileUtil.doUpFile(basePath + compressPath + fileName,
						imgcomp3)) {
					store.setImgSrc3(compressPath + fileName);
				}
			}
			systemLogService.saveSystemLog(request, "商家店铺管理", "新增或修改了店铺信息--"+service.findById(store.getBrandId().toString()).getName());
			tgStoreService.saveOrUpdate(store);
			if ("2".equals(tsSysuser.getType())) {
				service.changeAuding(store.getBrandId());
				return "findStoreInfo_SJ";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";
	}

	/**
	 * 得到商家店铺信息
	 * 
	 * @return
	 */
	public String findStoreInfo() {
		String id = RequestUtil.getParam(request, "id", "0");
		Long lid = Long.valueOf(id);
		store = tgStoreService.findStoreBybid(lid);
		if (store == null) {
			store = new TgStore();
			store.setBrandId(lid);
			return "addStore";
		}
		return "modifyStore";
	}

	/**
	 * 商家登陆得到店铺信息
	 * 
	 * @return
	 */
	public String findStoreInfo_SJ() {
		TgBrand brand = (TgBrand) RequestUtil.getLoginUserFromSession(request,
				"brandInfo");
		Long lid = brand.getId();
		store = tgStoreService.findStoreBybid(lid);
		if (store == null) {
			store = new TgStore();
			store.setBrandId(lid);
		}
		return "modifyStore_sj";
	}

	public String changeAdIndex() {
		try {
			Long sid = RequestUtil.getParam(request, "sid", 0l);
			Integer sweight = RequestUtil.getParam(request, "sweight", 0);
			Long tid = RequestUtil.getParam(request, "tid", 0l);
			Integer tweight = RequestUtil.getParam(request, "tweight", 0);
			Integer sindex = RequestUtil.getParam(request, "sindex", 0);
			Integer tindex = RequestUtil.getParam(request, "tindex", 0);
			service.modifyAdIndex(sid, tid, sweight, tweight, sindex, tindex);
			systemLogService.saveSystemLog(request, "广告位权重管理", "修改权重--"+service.findById(sid.toString()).getName());
			response.getWriter().print("1");
		} catch (Exception e) {
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			log.error("修改广告位排序出错", e);
		}
		return null;
	}

	public String changePinggouIndex() {
		try {
			Long sid = RequestUtil.getParam(request, "sid", 0l);
			Integer sweight = RequestUtil.getParam(request, "sweight", 0);
			Long tid = RequestUtil.getParam(request, "tid", 0l);
			Integer tweight = RequestUtil.getParam(request, "tweight", 0);
			Integer sindex = RequestUtil.getParam(request, "sindex", 0);
			Integer tindex = RequestUtil.getParam(request, "tindex", 0);
			service.modifyPingouIndex(sid, tid, sweight, tweight, sindex,
					tindex);
			systemLogService.saveSystemLog(request, "拼购首页推荐", "修改权重--"+service.findById(sid.toString()).getName());
			response.getWriter().print("1");
		} catch (Exception e) {
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			log.error("修改首页拼购推荐排序出错", e);
		}
		return null;
	}

	public String deleteInformationAd() {
		try {
			Long categoryId = RequestUtil.getParam(request, "categoryId", 0l);
			Long brandId = RequestUtil.getParam(request, "brandId", 0l);
			Long typeId = RequestUtil.getParam(request, "typeId", -1l);
			tgBrand = service.findById(brandId+"");
			if(categoryId==0){
			    systemLogService.saveSystemLog(request, "全站热点广告", "删除--"+tgBrand.getName());
			}
			if(categoryId!=0){
			    if(typeId==-2){
	                systemLogService.saveSystemLog(request, "种类资讯广告", "删除--"+tgBrand.getName());
	            }else{
			       systemLogService.saveSystemLog(request, "行业资讯广告", "删除--"+tgBrand.getName());
	            }
			}
			service.deleteInformationAd(categoryId, brandId, typeId);
			response.getWriter().print("1");
		} catch (Exception e) {
			log.error("删除资讯权广告失败", e);
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	public String changeAd() {
		try {
			Long sid = RequestUtil.getParam(request, "sid", 0l);
			Long tid = RequestUtil.getParam(request, "tid", 0l);
			service.modifyAd(sid, tid);
			response.getWriter().print("1");
		} catch (Exception e) {
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			log.error("替换广告位品牌出错", e);
		}
		return null;
	}

	public String changePingouIndex() {
		try {
			Long sid = RequestUtil.getParam(request, "sid", 0l);
			Long tid = RequestUtil.getParam(request, "tid", 0l);
			Long pid = RequestUtil.getParam(request, "pid", 0l);
			Long cid = RequestUtil.getParam(request, "cid", 0l);
			service.changePingouIndex(sid, tid, pid, cid);
			response.getWriter().print("1");
		} catch (Exception e) {
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			log.error("替换广告位品牌出错", e);
		}
		return null;
	}

	public String addPingouAd() {
		try {
			Long bid = RequestUtil.getParam(request, "bid", 0l);
			Long pingouId = RequestUtil.getParam(request, "pingouId", 0l);
			Long cid = RequestUtil.getParam(request, "cid", 0l);
			Integer index = RequestUtil.getParam(request, "index", 0);
			int weight = 11 - index;
			service.addPinggouAd(bid, pingouId, cid, weight);
			response.getWriter().print("1");
		} catch (Exception e) {
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			log.error("添加首页拼购推荐", e);
		}
		return null;
	}

	/**
	 * 活动信息查询
	 * 
	 * @return
	 */
	public String searchFavorable() {
		String page = RequestUtil.getParam(request, "page", "1");
		String row = RequestUtil.getParam(request, "rows", "10");
		String name = RequestUtil.getParam(request, "name", "");
		String auding = RequestUtil.getParam(request, "auding", "");
		String brandId = RequestUtil.getParam(request, "bid", "0");

		Map<String, String> parameMap = new HashMap<String, String>();
		parameMap.put("page", page);
		parameMap.put("brandId", brandId);
		parameMap.put("row", row);
		parameMap.put("name", name);
		parameMap.put("auding", auding);
		int count = tgFavorableService.count(parameMap);
		if (count != 0) {
			total = count;
			List<TgFavorable> bradlist = tgFavorableService
					.findFavorable(parameMap);
			rows = bradlist;
		}
		return Contants.JSONSTRING_RESULT_NAME;
	}

	/**
	 * 新增、修改活动
	 * 
	 * @return
	 */
	public String searchFavorableById() {
		String bid = RequestUtil.getParam(request, "bid", "0");
		String id = RequestUtil.getParam(request, "id", "0");
		favorable = tgFavorableService.read(Long.valueOf(id));
		if (null != favorable) {
			favorable.setStartTimeString(DateTimeUtil.switchDateToString(
					favorable.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
			favorable.setEndTimeString(DateTimeUtil.switchDateToString(
					favorable.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
			return "modifyFavorable";
		} else {
			favorable = new TgFavorable();
			favorable.setBrandId((Long.valueOf(bid)));
			return "addFavorable";
		}
	}

	/**
	 * 新增、修改 活动信息
	 * 
	 * @return
	 */
	public String addFavorable() {
		TsSysuser tsSysuser = (TsSysuser) RequestUtil.getLoginUserFromSession(
				request, Contants.SESSION_USER);
		try {
		    favorable.setAutding("0");
			String basePath = request.getSession().getServletContext()
					.getRealPath("/");
			String compressPath = XmlUtil.getValue("imgPath", "sysConfig")
					+ "/";
			String fileName = "";
			if (imgcomp != null) {
				fileName = new Date().getTime()
						+ imgcompFileName.substring(imgcompFileName
								.lastIndexOf("."));
				if (FileUtil.doUpFile(basePath + compressPath + fileName,
						imgcomp)) {
					favorable.setImgSrc(compressPath + fileName);
				}
			}
			if("1".equals(tsSysuser.getSource())){
			    favorable.setAutding("1");
			}
			systemLogService.saveSystemLog(request, "商家活动管理", "新增或修改了活动信息--"+service.findById(favorable.getBrandId().toString()).getName());
			tgFavorableService.saveOrUpdate(favorable);
		} catch (Exception e) {
			e.printStackTrace();
		}
		bid = favorable.getBrandId();
		if ("2".equals(tsSysuser.getType()))
			return "manageFavorable_SJ";
		return "addFavorablesuccess";
	}

	public String deleteFavorable() {
		String idString = RequestUtil.getParam(request, "idString", "");
		boolean isFlag = false;
		String[] delteid = idString.split("_");
		try {
			for (int i = 0; i < delteid.length; i++) {
				systemLogService.saveSystemLog(request, "商家活动管理", "删除活动信息--"+service.findById(tgFavorableService.read(Long.valueOf(delteid[i])).getBrandId().toString()).getName());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		isFlag = service.deleteFavorable(idString);
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		if (isFlag){
			message = "删除成功";
		}else
			message = "删除失败";
		StringBuffer sb = new StringBuffer("[");
		sb.append("{\"message\":\"" + message + "\"" + "}");
		sb.append("]");

		try {
			out = response.getWriter();
			out.println(sb.toString());
		} catch (IOException e) {

			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 核实活动
	 * 
	 * @return
	 */
	public String audFavorable() {
		String idString = RequestUtil.getParam(request, "idString", "");
		String autding = RequestUtil.getParam(request, "autding", "");
		boolean isFlag = false;
		isFlag = service.audFavorable(idString, autding);
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		if (isFlag)
			message = "核实成功";
		else
			message = "核实失败";
		StringBuffer sb = new StringBuffer("[");
		sb.append("{\"message\":\"" + message + "\"" + "}");
		sb.append("]");

		try {
			out = response.getWriter();
			out.println(sb.toString());
		} catch (IOException e) {

			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 案例信息查询
	 * 
	 * @return
	 */
	public String searchcases() {
		String page = RequestUtil.getParam(request, "page", "1");
		String row = RequestUtil.getParam(request, "rows", "10");
		String name = RequestUtil.getParam(request, "name", "");
		String auding = RequestUtil.getParam(request, "auding", "");
		String brandId = RequestUtil.getParam(request, "bid", "0");

		Map<String, String> parameMap = new HashMap<String, String>();
		parameMap.put("page", page);
		parameMap.put("brandId", brandId);
		parameMap.put("row", row);
		parameMap.put("name", name);
		parameMap.put("auding", auding);
		int count = tgCaseService.count(parameMap);
		if (count != 0) {
			total = count;
			List<TgCase> bradlist = tgCaseService.findcases(parameMap);
			rows = bradlist;
		}
		return Contants.JSONSTRING_RESULT_NAME;
	}

	/**
	 * 新增、修改活动 案例
	 * 
	 * @return
	 */
	public String searchcasesById() {
		String bid = RequestUtil.getParam(request, "bid", "0");
		String id = RequestUtil.getParam(request, "id", "0");
		cases = tgCaseService.read(Long.valueOf(id));
		if (null != cases) {
			return "modifycases";
		} else {
			cases = new TgCase();
			cases.setBrandId((Long.valueOf(bid)));
			return "addcases";
		}
	}

	/**
	 * 新增、修改 案例信息
	 * 
	 * @return
	 */
	public String addcases() {
		TsSysuser tsSysuser = (TsSysuser) RequestUtil.getLoginUserFromSession(
				request, Contants.SESSION_USER);
		try {
			String basePath = request.getSession().getServletContext()
					.getRealPath("/");
			String compressPath = XmlUtil.getValue("imgPath", "sysConfig")
					+ "/";
			String fileName = "";
			if (imgcomp != null) {
				fileName = new Date().getTime()
						+ imgcompFileName.substring(imgcompFileName
								.lastIndexOf("."));
				if (FileUtil.doUpFile(basePath + compressPath + fileName,
						imgcomp)) {
					cases.setImgSrc(compressPath + fileName);
				}
			}
			if (cases.getId() <= 0l) {
				cases.setId(null);
			}
			if (null == cases.getCreateTime())
				cases.setCreateTime(new Date());
			systemLogService.saveSystemLog(request, "商家案例管理", "新增或修改了案例信息--"+service.findById(cases.getBrandId().toString()).getName());
			tgCaseService.saveOrUpdate(cases);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if ("2".equals(tsSysuser.getType())) {
			// service.changeAuding(store.getBrandId());
			return "manageCase_SJ";
		}
		return "addcasessuccess";
	}

	public String deletecases() {
		String idString = RequestUtil.getParam(request, "idString", "");
		boolean isFlag = false;
		String[] delteid = idString.split("_");
		try {
			for (int i = 0; i < delteid.length; i++) {
				systemLogService.saveSystemLog(request, "商家案例管理", "删除案例信息--"+service.findById(tgCaseService.read(Long.valueOf(delteid[i])).getBrandId().toString()).getName());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		isFlag = service.deletecases(idString);
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		if (isFlag){
			message = "删除成功";
		}else
			message = "删除失败";
		StringBuffer sb = new StringBuffer("[");
		sb.append("{\"message\":\"" + message + "\"" + "}");
		sb.append("]");

		try {
			out = response.getWriter();
			out.println(sb.toString());
		} catch (IOException e) {

			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 临时：优惠活动，案例
	 * 
	 * @return
	 */
	public String activityandcase() {
		try {
			List<TgBrand> list = service.findAllBrand();
			ActionContext context = ActionContext.getContext();
			context.put("tglist", list);
			String id = RequestUtil.getParam(request, "id", "");
			String type = RequestUtil.getParam(request, "type", "");
			TgInformation information = new TgInformation();
			if ("1".equals(type)) {
				TgFavorable fav = tgFavorableService.read(new Long(id));
				information.setTitle(fav.getTitle());
				information.setContent(fav.getContent());
				information.setThe1(DateTimeUtil.getDateToString(fav.getStartTime(), "yyyy-MM-dd kk:mm:ss"));
			    information.setThe2(DateTimeUtil.getDateToString(fav.getEndTime(), "yyyy-MM-dd kk:mm:ss"));
			    information.setCreatTimeStr(DateTimeUtil.getDateToString(fav.getCreateTime(), "yyyy-MM-dd kk:mm:ss"));
			}
			if ("2".equals(type)) {
				TgCase tgcase = tgCaseService.read(new Long(id));
				information.setTitle(tgcase.getTitle());
				information.setContent(tgcase.getContent());
				information.setCreatTimeStr(tgcase.getCreatTimStr());
			}
			if ("3".equals(type)) {
				TgProduct product = productService.read(new Long(id));
				information.setTitle(product.getTitle());
				information.setContent(product.getContent());
				information.setCreatTimeStr(product.getCreateTimeString());
			}
			ActionContext.getContext().put("information", information);
			ActionContext.getContext().put("categoryname", "");
			ActionContext.getContext().put("type", type);
		} catch (Exception e) {
			log.error("", e);
		}
		return "showzixun";
	}

	/**
	 * 查看商家咨询
	 */
	public String showShopmessager() {
		String id = RequestUtil.getParam(request, "id", "0");
		sMessage = shoperMessageService.findById(id);
		return "showShopmessager";
	}

	public String showShopmessagerTojson() {
		String id = RequestUtil.getParam(request, "id", "0");
		sMessage = shoperMessageService.findById(id);
		try {
			response.getWriter().print(JSONArray.fromObject(sMessage));
		} catch (Exception e) {
			log.error("根据行业获取资讯信息", e);
		}
		return null;
	}

	public String brandCategoryWeightIndex() {
		try {
			ActionContext context = ActionContext.getContext();
			context.put("categoryList", MemoryData.getCategoryList());
		} catch (Exception e) {
			log.error("转向行业资讯广告出错", e);
		}
		return "brandCategoryWeightIndex";
	}

	public String findAllBrandIndex() {
		try {
			Long categoryId = RequestUtil.getParam(request, "categoryId",
					MemoryData.getCategoryList().get(0).getId());
			int page = RequestUtil.getParam(request, "page", 1);
			int limit = RequestUtil.getParam(request, "rows", 10);
			PageUtil pu = service.findBrand(categoryId, -1l, page, limit);
			total = pu.getTotalRecords();
			rows = pu.getList();
		} catch (Exception e) {
			log.error("行业资讯广告检索出错", e);
		}
		return Contants.JSONSTRING_RESULT_NAME;
	}

	public TgBrand getTgBrand() {
		return tgBrand;
	}

	public void setTgBrand(TgBrand tgBrand) {
		this.tgBrand = tgBrand;
	}

	public TsSysuser getUser() {
		return user;
	}

	public void setUser(TsSysuser user) {
		this.user = user;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public File getImglog() {
		return imglog;
	}

	public void setImglog(File imglog) {
		this.imglog = imglog;
	}

	public String getImglogFileName() {
		return imglogFileName;
	}

	public void setImglogFileName(String imglogFileName) {
		this.imglogFileName = imglogFileName;
	}

	public File getImgpic() {
		return imgpic;
	}

	public void setImgpic(File imgpic) {
		this.imgpic = imgpic;
	}

	public String getImgpicFileName() {
		return imgpicFileName;
	}

	public void setImgpicFileName(String imgpicFileName) {
		this.imgpicFileName = imgpicFileName;
	}

	public List getRows() {
		return rows;
	}

	public void setRows(List rows) {
		this.rows = rows;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long getCategoryId() {
		return categoryId;
	}

	public void setCategoryId(Long categoryId) {
		this.categoryId = categoryId;
	}

	public String[] getTypeId() {
		return typeId;
	}

	public void setTypeId(String[] typeId) {
		this.typeId = typeId;
	}

	public TgStore getStore() {
		return store;
	}

	public void setStore(TgStore store) {
		this.store = store;
	}

	public File getImgcomp() {
		return imgcomp;
	}

	public void setImgcomp(File imgcomp) {
		this.imgcomp = imgcomp;
	}

	public String getImgcompFileName() {
		return imgcompFileName;
	}

	public void setImgcompFileName(String imgcompFileName) {
		this.imgcompFileName = imgcompFileName;
	}

	public TgFavorable getFavorable() {
		return favorable;
	}

	public void setFavorable(TgFavorable favorable) {
		this.favorable = favorable;
	}

	public TgCase getCases() {
		return cases;
	}

	public void setCases(TgCase cases) {
		this.cases = cases;
	}

	public ShoperMessage getSMessage() {
		return sMessage;
	}

	public void setSMessage(ShoperMessage message) {
		sMessage = message;
	}

	public File getImgcomp1() {
		return imgcomp1;
	}

	public void setImgcomp1(File imgcomp1) {
		this.imgcomp1 = imgcomp1;
	}

	public String getImgcomp1FileName() {
		return imgcomp1FileName;
	}

	public void setImgcomp1FileName(String imgcomp1FileName) {
		this.imgcomp1FileName = imgcomp1FileName;
	}

	public File getImgcomp2() {
		return imgcomp2;
	}

	public void setImgcomp2(File imgcomp2) {
		this.imgcomp2 = imgcomp2;
	}

	public String getImgcomp2FileName() {
		return imgcomp2FileName;
	}

	public void setImgcomp2FileName(String imgcomp2FileName) {
		this.imgcomp2FileName = imgcomp2FileName;
	}

	public File getImgcomp3() {
		return imgcomp3;
	}

	public void setImgcomp3(File imgcomp3) {
		this.imgcomp3 = imgcomp3;
	}

	public String getImgcomp3FileName() {
		return imgcomp3FileName;
	}

	public void setImgcomp3FileName(String imgcomp3FileName) {
		this.imgcomp3FileName = imgcomp3FileName;
	}

	public Long getBid() {
		return bid;
	}

	public void setBid(Long bid) {
		this.bid = bid;
	}

}
